package com.dup.jxlh.admin.service.auth;

import com.dup.jxlh.admin.entities.auth.AuthInfo;
import com.dup.jxlh.admin.entities.auth.AuthUser;
import com.dup.jxlh.admin.entities.auth.AuthPerm;
import com.dup.jxlh.api.enums.ResultEnum;
import com.dup.jxlh.api.exception.AppException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("authDetailsService")
public class AuthDetailsService implements UserDetailsService {
    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        AuthInfo authInfo = authService.findByPhone(username);
        if (authInfo == null) {
            throw new AppException(ResultEnum.USER_FOUND_ERROR);
        }

        if (!authInfo.getEnable()) {
            throw new AppException(ResultEnum.USER_ENABLE_ERROR);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        ArrayList<AuthPerm> permList = authService.getAuthPerms(authInfo.getRoleId());
        if (!permList.isEmpty()) {
            for (AuthPerm perm : permList) {
                authorities.add(new SimpleGrantedAuthority(perm.getName()));
            }
        }
        AuthUser authUser = new AuthUser(authInfo.getPhone(), authInfo.getPassword(), authorities);
        authUser.setCompanyId(authInfo.getCompanyId());
        authUser.setDepartmentId(authInfo.getDepartmentId());
        authUser.setId(authInfo.getId());
        authUser.setLevel(authInfo.getLevel());
        authUser.setRealname(authInfo.getRealname());
        return authUser;
    }
}
